package com.mz361.admin.market.controller;

import com.mz361.admin.market.domain.Customer;
import com.mz361.admin.market.domain.Project;
import com.mz361.admin.market.service.CustomerService;
import com.mz361.admin.market.service.ProjectService;
import com.mz361.admin.market.validator.ProjectValid;
import com.mz361.common.enums.StatusEnum;
import com.mz361.common.utils.EntityBeanUtil;
import com.mz361.common.utils.ResultVoUtil;
import com.mz361.common.utils.StatusUtil;
import com.mz361.common.utils.StringUtil;
import com.mz361.common.vo.ResultVo;
import com.mz361.modules.system.domain.Dept;
import com.mz361.modules.system.domain.User;
import com.mz361.modules.system.service.DeptService;
import com.mz361.modules.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

/**
 * @author niceale
 * @ date 2024/11/04
 */
@Controller
@ApiIgnore
@RequestMapping("/market/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private UserService userService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("market:project:index")
    public String index(Model model, Project project) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", match -> match.contains());

        // 获取数据列表
        Example<Project> example = Example.of(project, matcher);
        Page<Project> list = projectService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/market/project/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("market:project:add")
    public String toAdd(Model model) {
        List<Customer> customers = customerService.findAll();
        Dept dept = deptService.getById(3L);
        List<User> userList = userService.findByDept(dept);
        Map<Long, String> userMap = new HashMap<>();
        for (User user : userList) {
            userMap.put(user.getId(), user.getNickname());
        }
        model.addAttribute("userList", userList);
        model.addAttribute("userMap", userMap);
        model.addAttribute("customers", customers);
        return "/market/project/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("market:project:edit")
    public String toEdit(@PathVariable("id") Project project, Model model) {
        List<Customer> customers = customerService.findAll();
        Dept dept = deptService.getById(3L);
        List<User> userList = userService.findByDept(dept);
        Map<Long, String> userMap = new HashMap<>();
        for (User user : userList) {
            userMap.put(user.getId(), user.getNickname());
        }
        if (StringUtil.notEmpty(project.getPartner())) {
            List<String> partners = new ArrayList<>();
            if (project.getPartner().contains(",")) {
                partners = Arrays.asList(project.getPartner().split(","));
            } else {
                partners.add(project.getPartner());
            }
            model.addAttribute("partners", partners);
        }
        model.addAttribute("customers", customers);
        model.addAttribute("userList", userList);
        model.addAttribute("userMap", userMap);
        model.addAttribute("project", project);
        return "/market/project/add";
    }

    /**
     * 保存添加/修改的数据
     *
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"market:project:add", "market:project:edit"})
    @ResponseBody
    public ResultVo save(@Validated ProjectValid valid, Project project) {
        // 复制保留无需修改的数据
        if (project.getId() != null) {
            Project beProject = projectService.getById(project.getId());
            EntityBeanUtil.copyProperties(beProject, project);
        } else {
            project.setNumbering(StringUtil.getAutoEntry("PJ"));
        }

        // 保存数据
        projectService.save(project);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("market:project:detail")
    public String toDetail(@PathVariable("id") Project project, Model model) {
        Dept dept = deptService.getById(3L);
        List<User> userList = userService.findByDept(dept);
        Map<Long, String> userMap = new HashMap<>();
        for (User user : userList) {
            userMap.put(user.getId(), user.getNickname());
        }
        if (StringUtil.notEmpty(project.getPartner())) {
            List<String> partners = new ArrayList<>();
            List<String> names = new ArrayList<>();
            if (project.getPartner().contains(",")) {
                partners = Arrays.asList(project.getPartner().split(","));
            } else {
                partners.add(project.getPartner());
            }
            partners.forEach(v -> {
                if (userMap.get(Long.valueOf(v)) != null) {
                    names.add(userMap.get(Long.valueOf(v)));
                }
            });
            model.addAttribute("partners", names);
        }
        model.addAttribute("project", project);
        return "/market/project/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("market:project:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (projectService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}